<?php
namespace api\modules\v1\models\group;

use api\modules\v1\models\Common;
use api\modules\v1\models\friend\Friend;
use api\modules\v1\models\friend\FriendApply;
use api\modules\v1\models\imUser\ImUser;
use api\modules\v1\models\imUser\ImUserLevel;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\im\Im;
use common\models\im\ImQrcode;
use common\models\imUserFund\MoneyLog;
use common\models\Patterns;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\StringHelper;

class Group extends \common\models\group\Group
{

    /**
     * 主动创建群聊
     * @return array
     */
    public function create() {
        $trans = static::getDb()->beginTransaction();
        $user = (new User()) -> checkUser();
        CacheKeys::checkFrequency("CREATE_GROUP_".$user['id'],1);

        try {
            $redis = Yii::$app->redis;

            $friendIds = Yii::$app->request->post('user_code',[]);
            $friendIds = array_unique($friendIds);
            if (!$friendIds) {
                throw new Exception('请选择好友！');
            }

            if (empty($user)) {
                throw new Exception('未知用户信息！');
            }

            $exists = $redis->get(CacheKeys::IM_CREATE_GROUP . $user['id']);
            if($exists){
                throw new Exception('您的速度太快了！');
            }
            $redis->set(CacheKeys::IM_CREATE_GROUP . $user['id'], true);

            $friendUsers = User::getObjectOneByWhere(['tx_code' => $friendIds])->with([
                'isFriend' => function ($q) use ($user) {
                    $q->where(['user_id' => $user['id']])->select(['id','friend_id','user_id']);
                },

            ])->asArray()->all();
            if (empty($friendUsers)) {
                throw new Exception('未知好友信息！');
            }

            // 创建群聊
            $groupData = $this->createImGroup($user,$friendUsers);

            $trans->commit();
            return Functions::formatRestAPI(0, '创建成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        } finally {
            $redis->del(CacheKeys::IM_CREATE_GROUP . $user['id']);
        }
    }

    /**
     * 群列表
     * @return array
     */
    public function getList()
    {
        try{
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',20);
            $account = (string) Yii::$app->request->get('account','');
            $in = (string) Yii::$app->request->get('in',0);    // 1-在群里  2-不在群里

            $user = (new User()) -> checkUser();

            // 该用户的群
            $groupIds = GroupUser::getFormArray(['user_id' => $user['id']],'group_id','group_id');
            $where = $andWhere = [];
            $where['status'] = Status::COMMON_RADIO_YES;
            $andWhere[] = ['or',
                // ['like','code',$account],
                // ['like','tx_code',$account],
                ['like','name',$account],
            ];
            if ($in) {
                if ($in == Status::COMMON_RADIO_YES) {
                    $andWhere[] = ['in','id',$groupIds];
                }

                if ($in == Status::COMMON_RADIO_NO) {
                    $andWhere[] = ['not in','id',$groupIds];
                }
            }


            $count = static::getCountByAndWhere($where,$andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'id DESC', $offset, $size)->with([

            ])
                ->asArray()->all();
            $result = [];
            foreach ($list as $v) {
                $result[] = [
                    'id' => (int) $v['id'],
                    'group_code' => $v['code'] ?: '',
                    'group_tx_code' => $v['tx_code'] ?: '',
                    'group_name' => $v['name'] ?: '',
                    'group_pic' => static::getImages($v['image']),
                    'group_qr_code' => static::getImages($v['qr_code']),
                    'notice' => $v['notice'] ?: '',
                    'shut_up' => $v['is_shut_up'] ?? Status::COMMON_RADIO_NO,
                    'create_time' => $v['create_time'] ?: '',
                ];
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 获取群信息
     * @param string $groupTxCode
     * @return array
     */
    public function info($groupTxCode = '')
    {
        try{

            if (empty($groupTxCode)) {
                throw new Exception('参数错误');
            }

            $where = $andWhere = [];
            $where['tx_code'] = $groupTxCode;

            $info = static::getObjectByAndWhere($where,$andWhere)->asArray()->one();

            $user = (new User()) -> checkUser();
            $groupUser = GroupUser::getOneByWhere(['group_tx_code' => $groupTxCode,'user_id' => $user['id']]);

            $data = [
                'id' => (int) $info['id'],
                'group_code' => $info['code'] ?: '',
                'group_tx_code' => $info['tx_code'] ?: '',
//                'group_name' => Functions::deEmoji($info['name']),
                'group_name' => $info['name'],
                'group_pic' => static::getImages($info['image']),
                'group_qr_code' => static::getImages($info['qr_code']),
                'notice' => $info['notice'] ?: '',
                'shut_up' => (int) ($info['is_shut_up'] ?? Status::COMMON_RADIO_NO),
                'create_time' => $info['create_time'] ?: '',
                'user_type'=> $groupUser['user_type']?:'',
                'user_type_name' => Status::GROUP_USER_TYPE_MAP[$groupUser['user_type']]?:'',
                'self_shut_up' => (int) ($groupUser['is_shut_up'] ?? Status::COMMON_RADIO_NO),
                'is_add_friend' => (int) ($info['is_add_friend'] ?? Status::COMMON_RADIO_NO),
                'is_invite_friend' => (int) ($info['is_invite_friend'] ?? Status::COMMON_RADIO_NO),
                'show_exclusive_red_packet' => (int) ($info['show_exclusive_red_packet'] ?? Status::COMMON_RADIO_NO),
                'is_show_qr_code' => (int) ($info['is_show_qr_code'] ?? Status::COMMON_RADIO_NO),
                'is_show_user_name' => (int) ($info['is_show_user_name'] ?? Status::COMMON_RADIO_NO),
                'status' => (int) ($info['status'] ?? Status::COMMON_RADIO_NO),
                'user_num' => (int) ($info['user_num']),
            ];


            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 获取群信息
     * @param string $groupTxCode
     * @return array
     */
    public function getGroupUserNum($groupTxCode = '')
    {
        try{

            if (empty($groupTxCode)) {
                throw new Exception('参数错误');
            }

            $where = $andWhere = [];
            $where['tx_code'] = $groupTxCode;

            $info = static::getObjectByAndWhere($where,$andWhere)->asArray()->one();

            $data = [
                'user_num' => (int) ($info['user_num']),
            ];


            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 修改群信息 - 群头像 - 群名称 - 群公告
     * @return array
     */
    public function updateInfo() {
        $trans = static::getDb()->beginTransaction();

        try {

            $redis = Yii::$app->redis;
            $user = (new User()) -> checkUser();

            $groupTxCode = Yii::$app->request->post('group_tx_code','');
            $image = Yii::$app->request->post('image','');
            $name = Yii::$app->request->post('name','');
            $notice = Yii::$app->request->post('notice','');

            $isAddFriend = Yii::$app->request->post('is_add_friend','');
            $isInviteFriend = Yii::$app->request->post('is_invite_friend','');
            $showExclusiveRedPacket = Yii::$app->request->post('show_exclusive_red_packet','');
            $isShowQrCode = Yii::$app->request->post('is_show_qr_code','');
            $isShowUserName = Yii::$app->request->post('is_show_user_name','');
            $isAutoEnter = Yii::$app->request->post('is_auto_enter', 0);

            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            if (!$image && !$name && !$notice && !$isAddFriend && !$isInviteFriend && !$showExclusiveRedPacket && !$isShowQrCode && !$isShowUserName && !$isAutoEnter) {
                throw new Exception('参数错误！');
            }

            $groupInfo = static::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([
            ])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = GroupUser::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([
            ])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }

            if ($groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_HOME && $groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_MANAGE) {
                throw new Exception('您不是群主或者管理员，不可修改！');
            }

            $updateData = [];
            $updateImGroupData = $updateImGroupDefineData = [];
            if ($image) {
                $updateData['image'] = $image;
                $updateData['is_upload_image'] = Status::COMMON_RADIO_YES;

                $updateImGroupData['FaceUrl'] = static::getImages($image);
            }

            if ($name) {
//                $updateData['name'] = Functions::enEmoji($name);
                $updateData['name'] = $name;
                $updateImGroupData['Name'] = $name;
            }

            if ($notice) {
                $updateData['notice'] = $notice;
                $updateImGroupData['Notification'] = $notice;
            }


            if ($isAddFriend) {
                $updateData['is_add_friend'] = $isAddFriend;
                $updateImGroupDefineData['is_add_friend'] = (string) $isAddFriend;
            }

            if ($isInviteFriend) {
                $updateData['is_invite_friend'] = $isInviteFriend;
                $updateImGroupDefineData['is_invite_friend'] = (string) $isInviteFriend;
            }

            if ($showExclusiveRedPacket) {
                $updateData['show_exclusive_red_packet'] = $showExclusiveRedPacket;
                $updateImGroupDefineData['exclusive_red'] = (string) $showExclusiveRedPacket;
            }

            if ($isShowQrCode) {
                $updateData['is_show_qr_code'] = $isShowQrCode;
                $updateImGroupDefineData['is_show_qr_code'] = (string) $isShowQrCode;
            }

            if ($isShowUserName) {
                $updateData['is_show_user_name'] = $isShowUserName;
                $updateImGroupDefineData['is_show_user_n'] = (string) $isShowUserName;
            }

            if ($isAutoEnter) {
                $updateData['is_auto_enter'] = $isAutoEnter;
                $updateImGroupDefineData['is_auto_enter'] = (string) $isAutoEnter;
            }

            if ($updateData) {
                $res = static::updateData($updateData,['id' => $groupInfo['id']]);
                if ($res === false) {
                    throw new Exception('修改失败');
                }
            }

            if ($updateImGroupData || $updateImGroupDefineData) {
                // 更新IM群信息
                (new Im())->updateImGroup($groupInfo['tx_code'], $updateImGroupData, $updateImGroupDefineData);
            }

            // 发送im消息
            $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
            $publicGroupMessage['oneTxCode'] = $user['tx_code'];
            $publicGroupMessage['oneNIckName'] = $user['nick_name'];
            if ($image) {
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_EDIT_PIC;
                $publicGroupMessage['content'] = "用户".$user['nick_name']."修改了群头像！";
            }

            if ($name) {
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_EDIT_NAME;
                $publicGroupMessage['content'] = "用户".$user['nick_name']."将群名改为：".$name;
            }

            if ($notice) {
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_EDIT_NOTICE;
                $publicGroupMessage['content'] = "用户".$user['nick_name']."将群公告改为：".$notice;
            }
            if (isset($publicGroupMessage['content']) && !empty($publicGroupMessage['content'])) {
                (new Im())->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);
            }


            $trans->commit();
            return Functions::formatRestAPI(0, '修改成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 解散群
     * @param string $groupTxCode
     * @return array
     */
    public function del($groupTxCode = "") {
        $trans = static::getDb()->beginTransaction();

        try {

            $groupTxCode = $groupTxCode ? $groupTxCode : Yii::$app->request->post('group_tx_code',"");
            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            $redis = Yii::$app->redis;
            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $groupInfo = static::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([
            ])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }
            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = GroupUser::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([
            ])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }

            if ($groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_HOME) {
                throw new Exception('您不是群主，不可解散群！');
            }

            // 群成员信息  群申请信息全都删除 与 群信息
            $resGroupUserDel = GroupUser::deleteAll(['group_id' => $groupInfo['id']]);
            if ($resGroupUserDel === false) {
                throw new Exception('群解散失败！');
            }

            $resGroupApplyDel = GroupApply::deleteAll(['group_id' => $groupInfo['id']]);
            if ($resGroupApplyDel === false) {
                throw new Exception('群解散失败！');
            }

            $resGroupDel = static::deleteAll(['id' => $groupInfo['id']]);
            if ($resGroupDel === false) {
                throw new Exception('群解散失败！');
            }


            // IM解散群
            $resImDel = (new Im())->delGroup($groupInfo['tx_code']);
            if (!$resImDel) {
                throw new Exception('群解散失败！');
            }

            // 发送未读通知
            FriendApply::notReadApplyNum($user['id'], $groupInfo['id']);

            $trans->commit();
            return Functions::formatRestAPI(0, '群解散成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 转让群
     * @return array
     */
    public function transGroup() {
        $trans = static::getDb()->beginTransaction();

        try {
            $groupTxCode = Yii::$app->request->post('group_tx_code',"");
            $userId = Yii::$app->request->post('user_code',0);
            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            if (!$userId) {
                throw new Exception('参数错误！');
            }

            $redis = Yii::$app->redis;
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            CacheKeys::checkFrequency("TRANS_GROUP_".$user['id'],1);

            $groupInfo = static::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([
            ])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = GroupUser::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([

            ])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }

            if ($groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_HOME) {
                throw new Exception('您不是群主，无法转让该群！');
            }

            $transGroupUser = GroupUser::getObjectOneByWhere([
                'user_tx_code' => $userId,
                'group_id' => $groupInfo['id'],
            ])->with([
                'user' => function ($q) {
                    $q->select(['id','login_name','user_face','nick_name','tx_code','user_code']);
                }
            ])->asArray()->one();
            if (empty($transGroupUser)) {
                throw new Exception('转让的群成员不存在，不可转让！');
            }
            $transUser = ArrayHelper::getValue($transGroupUser,'user',[]);

            // 更新群
            $updateGroupData['user_tx_code'] = $transUser['tx_code'];
            $updateGroupData['user_id'] = $transUser['id'];
            $updateGroupData['user_code'] = $transUser['user_code'];
            $updateGroupData['user_phone'] = $transUser['login_name'];
            $resGroupUpdate = static::updateData($updateGroupData,['id' => $groupInfo['id']]);
            if ($resGroupUpdate === false) {
                throw new Exception('转让失败！');
            }

            // 更新群成员
            $updateGroupUserData = [];
            $updateGroupUserData['user_type'] = Status::GROUP_USER_TYPE_HOME;
            $resGroupUserUpdate = GroupUser::updateData($updateGroupUserData,['id' => $transGroupUser['id']]);
            if ($resGroupUserUpdate === false) {
                throw new Exception('转让失败！');
            }

            $updateGroupUserData = [];
            $updateGroupUserData['user_type'] = Status::GROUP_USER_TYPE_NORMAL;
            $resGroupUserUpdate = GroupUser::updateData($updateGroupUserData,['id' => $groupUserInfo['id']]);
            if ($resGroupUserUpdate === false) {
                throw new Exception('转让失败！');
            }

            // 更新IM群成员信息
            $updateImGroupUserData['Role'] = 'Member';
            $resUpdateImGroupUserData = (new Im())->updateImGroupUser($groupInfo['tx_code'], $groupUserInfo['user_tx_code'],$updateImGroupUserData);
            if (!$resUpdateImGroupUserData) {
                throw new Exception('操作失败！');
            }


            // IM转让
            $resImDel = (new Im())->transGroup($groupInfo['tx_code'],$transUser['tx_code']);
            if (!$resImDel) {
                throw new Exception('转让失败！');
            }


            $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
            $publicGroupMessage['oneTxCode'] = $user['tx_code'];
            $publicGroupMessage['oneNIckName'] = $user['nick_name'];
            $publicGroupMessage['oneNIckName'] = $transUser['tx_code'];
            $publicGroupMessage['oneNIckName'] = $transUser['nick_name'];
            $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_TRANS;
            $publicGroupMessage['content'] = "用户".$user['nick_name']."已将群转让给：".$transUser['nick_name'];
            (new Im())->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);


            // 发送未读通知
            FriendApply::notReadApplyNum($user['id'], $groupInfo['id']);

            $trans->commit();
            return Functions::formatRestAPI(0, '群转让成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 禁言 - 群禁言
     * @return array
     */
    public function shutUp() {
        $trans = static::getDb()->beginTransaction();

        try {
            $redis = Yii::$app->redis;
            $user = (new User()) -> checkUser();

            $groupTxCode = Yii::$app->request->post('group_tx_code',"");
            $state = Yii::$app->request->post('state',0);
            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            if (!$state) {
                throw new Exception('参数错误！');
            }

            if (!in_array($state,[Status::COMMON_RADIO_YES, Status::COMMON_RADIO_NO])) {
                throw new Exception('禁言状态不合法！');
            }


            $groupInfo = static::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([
            ])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }
            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = GroupUser::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([

            ])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }
            if ($groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_HOME && $groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_MANAGE) {
                throw new Exception('您不是群主或管理，无法操作！');
            }


            // 更新群
            $updateGroupData['is_shut_up'] = $state;
            $resGroupUpdate = static::updateData($updateGroupData,['id' => $groupInfo['id']]);
            if ($resGroupUpdate === false) {
                throw new Exception('操作失败！');
            }

            // IM
            $updateImGroupData['ShutUpAllMember'] = $state == Status::COMMON_RADIO_YES ? 'On' : 'Off';
            $updateImGroupDefineData['is_shut_up'] = (string) $state;
            $resImDel = (new Im())->updateImGroup($groupInfo['tx_code'], $updateImGroupData,$updateImGroupDefineData);
            if (!$resImDel) {
                throw new Exception('操作失败！');
            }

            $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
            $publicGroupMessage['oneTxCode'] = $user['tx_code'];
            $publicGroupMessage['oneNIckName'] = $user['nick_name'];
            if ($state == Status::COMMON_RADIO_YES) {
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_SHUT_UP_ON;
                $publicGroupMessage['content'] = "用户".$user['nick_name']."已设置全局禁言（不包含群主和管理员）！";
            } else {
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_SHUT_UP_OFF;
                $publicGroupMessage['content'] = "用户".$user['nick_name']."已取消全局禁言！";
            }
            (new Im())->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 设置管理员
     * @return array
     */
    public function setManage() {
        $trans = static::getDb()->beginTransaction();

        try {
            $redis = Yii::$app->redis;
            $user = (new User()) -> checkUser();

            $groupTxCode = Yii::$app->request->post('group_tx_code',"");
            $userId = Yii::$app->request->post('user_code',0);
            $identity = (string) Yii::$app->request->post('identity',0);  // 1- 群主 2-管理员 3-普通成员
            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            if (is_array($userId)) {
                throw new Exception('参数错误！');
            }

            if (!$userId) {
                throw new Exception('参数错误！');
            }


            if (!in_array($identity,[Status::GROUP_USER_TYPE_MANAGE, Status::GROUP_USER_TYPE_NORMAL])) {
                throw new Exception('身份不合法！');
            }

            $groupInfo = static::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([
            ])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }
            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = GroupUser::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([

            ])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }

            if ($groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_HOME ) {
                throw new Exception('您不是群主，无法操作！');
            }

            $handleUserInfo = GroupUser::getObjectByWhere([
                'user_tx_code' => $userId,
                'group_id' => $groupInfo['id'],
            ])->with([

            ])->asArray()->one();
            if (empty($handleUserInfo)) {
                throw new Exception('该用户不在群中！');
            }

            if ($handleUserInfo['user_type'] == Status::GROUP_USER_TYPE_HOME ) {
                throw new Exception('该用户是群主，无法操作！');
            }

            if ($identity == Status::GROUP_USER_TYPE_MANAGE) {
                $manageCount = GroupUser::getCountByWhere(['group_id' => $groupInfo['id'],'user_type' => Status::GROUP_USER_TYPE_MANAGE]);
                if ($manageCount >= 20) {
                    throw new Exception('群管理员不能超过20个！');
                }

                if ($handleUserInfo['user_type'] == Status::GROUP_USER_TYPE_MANAGE) {
                    throw new Exception('该成员已是管理员，无需重新设置！');
                }
            } else {
                if ($handleUserInfo['user_type'] == Status::GROUP_USER_TYPE_NORMAL) {
                    throw new Exception('该成员已是普通成员，无需重新设置！');
                }

            }

            // 更新群成员
            $updateGroupUserData['user_type'] = $identity;
            $resGroupUserUpdate = GroupUser::updateData($updateGroupUserData,['id' => $handleUserInfo['id']]);
            if ($resGroupUserUpdate === false) {
                throw new Exception('操作失败！');
            }

            // 修改im信息
            $updateImGroupUserData['Role'] = $identity == Status::GROUP_USER_TYPE_MANAGE ? 'Admin' : 'Member';
            $resUpdateImGroupUserData = (new Im())->updateImGroupUser($groupInfo['tx_code'], $handleUserInfo['user_tx_code'],$updateImGroupUserData);
            if (!$resUpdateImGroupUserData) {
                throw new Exception('操作失败！');
            }

            // 发送未读通知
            FriendApply::notReadApplyNum($user['id'], $groupInfo['id']);

            $trans->commit();
            return Functions::formatRestAPI(0, '设置成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

}
